package com.ht.api.call.func.impl.wwx;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 查询企微标签
 * @author asq
 * @createTime 2025年1月13日 22:19:08
 */
@Slf4j
public class WwxTagQueryFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "查询企微标签";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		
		// 获取查询参数
		String groupId = param.getStr("group_id");
		
		// 组装sql
		String sql = """
				SELECT
				  gt.group_id,
				  gt.group_name,
				  gt.tenant_appid group_appid,
				  gt.`order` gt_order,
				  t.id,
				  t.`name`,
				  t.tenant_appid appid, 
				  t.`order` 
				FROM
				  wx_tag t
				  INNER JOIN wx_group_tag gt ON t.group_id = gt.group_id 
				WHERE
				  gt.sys_deleted = 1 
				  AND t.sys_deleted = 1 %s
				ORDER BY
				  gt.`order` DESC,
				  t.`order` DESC
				""";
		String groupIdParam = StrUtil.isNotBlank(groupId) ? "AND gt.group_id = ? " : "";
		sql = String.format(sql, groupIdParam);

		// 获取查询参数
		List<String> params = new ArrayList<>();
		if (StrUtil.isNotBlank(groupIdParam)) {
			params.add(groupIdParam);
		}

		// 查询
		DbList list = Db.query(ds, sql, params);
		
		// 组装
		JSONArray groupTags = groupTags(list);
		return JSONUtil.createObj().set("list", groupTags);
	}
	
	/**
	 * 对查询结果进行分组处理，以展示树型结构
	 * @param tagList
	 * @return
	 */
	private JSONArray groupTags(DbList tagList) {
		Map<String, List<Entity>> groupedTags = tagList.stream()
				.collect(Collectors.groupingBy(tag -> {
						return tag.getStr("group_id") + "," + tag.getStr("group_name")
						+ "," + tag.getStr("group_appid")+ "," + tag.getStr("gt_order");
					}));
		
		JSONArray result = new JSONArray();
		groupedTags.forEach((groupIdAndName, list) -> {String[] groupArr = groupIdAndName.split(",");
	        JSONObject groupObject = new JSONObject();
	        groupObject.set("group_id", groupArr[0]);
	        groupObject.set("group_name", groupArr[1]);
	        groupObject.set("group_appid", groupArr[2]);
	        groupObject.set("group_order", groupArr[3]);
	        
	        JSONArray tagArray = new JSONArray();
	        list.forEach((entity) -> {
	            JSONObject tag = new JSONObject();
	            tag.set("id", entity.getStr("id"));
	            tag.set("name", entity.getStr("name"));
	            tag.set("appid", entity.getStr("appid"));
	            tag.set("order", entity.getStr("order"));
	            tagArray.put(tag);
	        });

	        groupObject.set("tag_group", tagArray);
	        result.put(groupObject);
		});
		return result;
	}
}
